#include "HufArc.h"

int clean_files (char * fileName,char * TMPfileName,int flag)
{
	int rc;
	char a[] = "XXXXXX";
	char * arcBack = NULL;
	if (flag & NEW_ARC)
	{
		if ((fileName) && (TMPfileName))
		{
			arcBack = (char *) calloc (strlen(fileName) + 7,sizeof(char));
			if (!arcBack)
				cl_exit (CLEAN_FILE,MEMORY_ERR,TMPfileName);
			strcat (arcBack,fileName);
			strcat (arcBack, a);
			arcBack = mktemp (arcBack);
			rc = rename (fileName,arcBack);
			if (!rc) 
			{
				rc = rename (TMPfileName,fileName);
				if (!rc) 
				{
					rc = remove (arcBack);
					if (!rc)
					{
						free (arcBack);
						return 0;
					} else {
						cl_exit ( CLEAN_FILE,ERR_ARC_DEL,TMPfileName);
						return 0;
					}
				} else {
					rename (arcBack,fileName);
					cl_exit ( CLEAN_FILE,ERR_TMP_ARC_REN, TMPfileName);
					return 0;
				}
			} else {
				cl_exit (CLEAN_FILE, ERR_ARC_REN, TMPfileName);
				return 0;
			}
		} 
		else {
			cl_exit (CLEAN_FILE, ERR_NULL_STR, TMPfileName);
			return 0;
		}
	} else {
		if (flag & NEW_ARC_2)
		{
			rc = rename (TMPfileName,fileName);
			if (rc)
			{
				cl_exit (CLEAN_FILE, ERR_ARC_REN, TMPfileName);
			}
		} else {

		if (flag & NEW_FILE)
		{
			if ((fileName) && (TMPfileName))
			{
				rc = rename (TMPfileName,fileName);
				if (!rc)
				{
					return 0;
				} else {
					cl_exit (CLEAN_FILE, ERR_FILE_REN, TMPfileName);
					return 0;
				}
			} else {
				cl_exit ( CLEAN_FILE,ERR_NULL_STR, TMPfileName);
				return 0;
			}
		}
	}
	}
	return 1;
}
	



